package mock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

/**
 *
 * @author vladimir 04.09.2013   11:33
 */

public class ApplicationContextProvider implements ApplicationContextAware {
    private static final Log log = LogFactory.getLog(ApplicationContextProvider.class);

    private static ApplicationContext applicationContext;

    private ApplicationContextProvider() {
    }

    public static ApplicationContext getApplicationContext() {
        Assert.state(applicationContext != null, "Application context holder is not initialized");
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ApplicationContextProvider.applicationContext != null) {
            log.warn("Application context holder was already initialized at least one time");
            return;
        }

        while (applicationContext.getParent() != null) {
            applicationContext = applicationContext.getParent();
        }
        ApplicationContextProvider.applicationContext = applicationContext;
    }
}